package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;

import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAddressBookService addressBookService;
    @Autowired
    private IOrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R submit(HttpSession session, @RequestBody Orders orders) {
        //获取用户id
        User loginPhone = (User) session.getAttribute("loginPhone");
        Long id = loginPhone.getId();
        //查询购物车数据
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, id);
        List<ShoppingCart> list = shoppingCartService.list(qw);
        //查询用户数据
        User user = userService.getById(id);
        //根据地址ID,查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //订单号
        long orderId = IdWorker.getId();
        //总价
        AtomicInteger amount = new AtomicInteger(0);

        // 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetails = list.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //组装订单数据
        //订单id
        orders.setId(orderId);
        //订单创建时间
        orders.setOrderTime(LocalDateTime.now());
        //订单结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(new BigDecimal(amount.get()));
        //总金额
        orders.setStatus(2);
        //用户id
        orders.setUserId(id);
        //订单号
        orders.setNumber(String.valueOf(orderId));
        //用户名
        orders.setUserName(user.getName());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //收货人联系电话
        orders.setPhone(addressBook.getPhone());
        //省+市+区域+详细地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表中加入数据
        ordersService.save(orders);
        //向订单明细表插入多条数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(qw);
        return R.success("下单成功");
    }

    /**
     * 订单分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R page(Integer page, Integer pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        //qw.like(StringUtils.isNotEmpty(number),Orders::getNumber,number);

        ordersService.page(pageInfo);
        List<Orders> orderList = pageInfo.getRecords();

        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders orders : orderList) {
            Long id = orders.getId();
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> orderDetailList = orderDetailService.list(lqw);

            OrdersDto ordersDto = new OrdersDto();
            BeanUtil.copyProperties(orders, ordersDto);
            ordersDto.setOrderDetails(orderDetailList);

            ordersDtos.add(ordersDto);
        }

        Map map = new HashMap<>();
        int total = (int) pageInfo.getTotal();
        map.put("total", total);
        map.put("records", ordersDtos);
        return R.success(map);
    }
}
